package com.chao.rsa2demo.encrypt.asymmetric;

import cn.hutool.core.util.StrUtil;
import com.chao.rsa2demo.encrypt.RSAException;
import com.chao.rsa2demo.encrypt.constant.EncryptConstants;
import com.chao.rsa2demo.encrypt.constant.ErrorEnum;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: cjp
 * @create: 2024-11-12 10:30
 * @description: 非对称加密算法管理类
 */
public class AsymmetricManager {

    private static final Map<String, IAsymmetricEncryptor> asymmetricManager = new ConcurrentHashMap<String, IAsymmetricEncryptor>();

    static {
        asymmetricManager.put(EncryptConstants.SIGN_TYPE_RSA, new RSAEncryptor());
        asymmetricManager.put(EncryptConstants.SIGN_TYPE_RSA2, new RSA2Encryptor());
//        asymmetricManager.put(Constants.SIGN_TYPE_SM2, new SM2Encryptor());
    }

    /**
     * Gets by name.
     *
     * @param type the type
     *
     * @return the by name
     *
     * @throws RSAException the alipay api exception
     */
    public static IAsymmetricEncryptor getByName(String type) throws RSAException {
        IAsymmetricEncryptor asymmetricEncryptor = null;

        if (!StrUtil.isEmpty(type)) {
            asymmetricEncryptor = asymmetricManager.get(type);
        }

        if (asymmetricEncryptor != null) {
            return asymmetricEncryptor;
        }

        throw new RSAException(String.format(ErrorEnum.SIGN_TYPE_ERROR.getErrMsg(), type));
    }

    public static Map<String, IAsymmetricEncryptor> getAsymmetricManager() {
        return asymmetricManager;
    }

    public static void putAsymmetricManager(String signType, IAsymmetricEncryptor asymmetricEncryptor) {
        asymmetricManager.put(signType, asymmetricEncryptor);
    }
}